package com.project.collectAPI.comm;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.project.collectAPI.config.DataSourceConfig;
import com.project.collectAPI.entity.*;
import com.project.collectAPI.entity.CreateUpdateClass.CreateUpdateClass;
import com.project.collectAPI.entity.ImageDownLoader.ImageDownLoader;
import com.project.collectAPI.entity.MeiTuan.MeituanGoods;
import com.project.collectAPI.entity.MeiTuan.SystemParam;
import com.project.collectAPI.entity.MeiTuanBatchDelete.MeiTuanBatchDelete;
import com.project.collectAPI.entity.MultiPois.MultiPois;
import com.project.collectAPI.entity.SuperMarket.HisTory;
import com.project.collectAPI.entity.SuperMarket.SuperMarketFirstClass;
import com.project.collectAPI.entity.SuperMarket.SuperMarketSecondClass;
import com.project.collectAPI.entity.UploadImageAPI.UploadImageAPI;
import com.project.collectAPI.entity.multiUpdateProduct.MultiUpdateProduct;
import com.project.collectAPI.entity.saleByTagIdAPI.saleByTagIdAPI;
import com.project.collectAPI.service.CurtaskforsupermarketService;
import com.project.collectAPI.service.SavedataService;
import com.sun.jna.platform.win32.WinDef;
import javafx.concurrent.Task;
import jdk.nashorn.internal.parser.JSONParser;
import lombok.SneakyThrows;
import okhttp3.Headers;
import org.apache.commons.lang.ArrayUtils;

import javax.annotation.Resource;
import javax.swing.*;
import javax.xml.crypto.Data;
import java.awt.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.Timer;
import java.util.concurrent.TimeUnit;

/**
 * @author Daniel 3955296@qq.com
 * @since 2023-07-20 00:07:35
 * @param
 * @param doNumn 工作次数
 * @return
 */
public class doWork {

    public static String storeName;
    public static Map<String,String> headers; //保存当前店铺headers信息

    public static volatile Boolean isCheckWorking=false; //检查是否开始工作
    public static int closeProgramNum=2; //为了避开广告,需要关闭程序再打开的次数,这里需要关闭2次
    public static int resetNum=1; //任务重试次数


    public static String lastItem=null; //最后一个菜单分类
    public static Map<String,String> newData=new HashMap<>(); //临时最新值
    public static Map<String,String> oldData=new HashMap<>(); //保存当前获取的最新值，用来判断是否到最底，如果新值和旧值相等，则是到了最后一条数据

    public static int waitTime=20; //等待数据请求的时间
    public static volatile Boolean interrupt=false;
    public static int EndNum=0; //数据到底后，最后的循环次数，如果3次都是同一值，则程序认为是到底了
    //递归调用启动器
    public static Timer timer=null;

    public static List<String> ClickIdsList=new ArrayList<>();

    public static volatile int isSameClick=0;

    //是否开始工作
    public static volatile boolean isStartWork=false;

    //是否创建二级级分类（true创建）
    public static volatile Boolean isSecondMode=false;

    //map ArrayList
    public static ArrayList<String> dataMapList=new ArrayList();

    @Resource
    public static SavedataService savedataService;

    //19693890 沃尔玛-上海市康桥店 上海市浦东新区祝桥镇施镇路256弄1号
    //19659841 沃尔玛-购物广场深圳香蜜湖店 深圳市福田区香梅北路2001号(香梅北地铁站D口步行60米)
    public static String storeIds= "19693890,19659841,19693891,19693892,19693569,19693568,19692302,19693717,19692338,19318566,19655599,19693571,19653817,19660018,19318808,19653384,19653815,19655453,19653814,19660329,19653816,\n" +
            "19653813,19659826,19318809,19655450,19653819,19653440,19653443,19653818,19318741,19653812,18836896,19660016,19692318,19659842,18667030,19692281,18667031,18674383";
    //public static String storeIds="19693890,19659841,19693891,19693892,19693569,19693568";
    public static String[] classCodeList={"sm01","sm02"}; //统一自定义分类 如 智能卡 sm01 智能火锅 sm02

    //当前app门店id
    public static volatile String curAppPoiCode=storeIds.split(",")[0]; //默认取

    //二级分类指定标识
    //public static volatile String secondDefined=null; //默认取

    //是否重启程序
    public static volatile Boolean isReStartProgram=false;

    //是否停止主线程i的for循环
    public static volatile Boolean isBreakFirstFor=false;

    /**
     * 工作任务
     * */
    public static void startDoTask(Robot robot) throws Exception {

        if(robot==null){
            robot=new Robot();
        }

        SuperMarketFirstClass f=new SuperMarketFirstClass();
        SuperMarketSecondClass sc=new SuperMarketSecondClass();
        String[] farr=f.getFirstArr();

        String taskName="";
        String curTaskStatue=""; //当前任务状态
        int pointX=0;
        int pointY=0;
        int delay100=1000;
        int delay500=500;
        int delay1000=1000;
        int delay1500=1500;
        String classCode="";

        boolean Line=false;

        //指定标识
        //获取分类名称
        String historyString= DataSourceConfig.getTaskHistory(); //6:1:乳品烘焙:4
        int firstIndex=Integer.valueOf(historyString.split(":")[0]); //一级分类数组索引
        taskName=farr[firstIndex].split(":")[0]; //0==水果蔬菜 水果蔬菜:130:210
        pointX = Integer.valueOf(farr[firstIndex].split(":")[1]);
        pointY = Integer.valueOf(farr[firstIndex].split(":")[2]);

        //批量店铺id
        String[] appPois = doWork.storeIds.split(","); //批量店铺id

        //读取数据库获取最近操作记录
        try{
            System.out.println("历史记录:"+historyString);
            if(!StringUtils.isEmpty(historyString)){

                HisTory.firstIndex=Integer.valueOf(historyString.split(":")[0]);
                HisTory.secondIndex=Integer.valueOf(historyString.split(":")[1]);
                HisTory.curTaskId=Integer.valueOf(historyString.split(":")[3]); //当前任务id，启动任务时就必须获取了
                curTaskStatue=DataSourceConfig.GetStatusById(HisTory.curTaskId);
                System.out.println("状态："+curTaskStatue);

                //移动窗体到左上角0,0
                try {
                    WinDef.HWND handle = AutoRobot.getWindowHandle("Chrome_WidgetWin_0", "沃尔玛");
                    System.out.println("handle:===>" + handle);
                    if (handle != null) {
                        //移动窗体
                        AutoRobot.moveWindowHandle(handle, 0, 0, 415, 780, false);

                        //是否一开始就显示分类，如果是则先隐藏一次
                        Point point=AutoRobot.FindTargetImagePositon(robot,"收起2.png");
                        System.out.println("查询是否有收起2.png"+point);
                        if(point.x!=-1 && point.y!=-1){
                            System.out.println("没找到收起2.png");
                            System.out.println(robot+"移动到一级分类点击："+taskName+",坐标："+pointX+","+pointY);
                            AutoRobot.MouseMove(robot,pointX,pointY);
                            robot.delay(1000);
                            AutoRobot.MouseClick(robot);
                            robot.delay(500);
                        }else{

                            //鼠标移动到分类
                            System.out.println("鼠标移动到分类");
                            AutoRobot.MouseMove(robot,150,750);
                            robot.delay(1000);
                            AutoRobot.MouseClick(robot);
                            robot.delay(1000);

                            point=AutoRobot.FindTargetImagePositon(robot,"收起2.png");
                            System.out.println("出现收起????"+point);

                            TimeUnit.MILLISECONDS.sleep(2000);

                            if(point.x!=-1 && point.y!=-1){
                                //移动到一级分类点击
                                System.out.println("移动到一级分类点击："+taskName+",坐标："+pointX+","+pointY);
                                AutoRobot.MouseMove(robot,pointX,pointY);
                                robot.delay(1000);
                                AutoRobot.MouseClick(robot);
                                robot.delay(500);
                            }else{

                                //重启小程序，默认第一次是打开全部分类的，这里要作个判断
                                point=AutoRobot.FindTargetImagePositon(robot,"收起2.png");
                                System.out.println("出现收起????"+point);
                                if(point.x!=-1 && point.y!=-1){
                                    //如果默认打开第一级分类，则直接点击一级分类
                                    System.out.println("移动到一级分类点击："+taskName+",坐标："+pointX+","+pointY);
                                    AutoRobot.MouseMove(robot,pointX,pointY);
                                    robot.delay(1000);
                                    AutoRobot.MouseClick(robot);
                                    robot.delay(500);
                                }else{
                                    //移动到全部，打开分类
                                    System.out.println("移动到全部，打开分类");
                                    AutoRobot.MouseMove(robot,396,177);
                                    robot.delay(1000);
                                    AutoRobot.MouseClick(robot);
                                    robot.delay(500);
                                    //移动到一级分类点击
                                    System.out.println("移动到一级分类点击else："+taskName+",坐标："+pointX+","+pointY);
                                    AutoRobot.MouseMove(robot,pointX,pointY);
                                    robot.delay(1000);
                                    AutoRobot.MouseClick(robot);
                                    robot.delay(500);
                                }
                            }
                            TimeUnit.MILLISECONDS.sleep(200);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("woWork移动窗体发生错误");
                }

                if(HisTory.secondIndex>=9){
                    Line=true;
                }


                //一级
                for (int i = HisTory.firstIndex; i < farr.length; i++) {

                    //检查是否调到了首页
                    //Check(robot);

                    //删除一级分类<<Start>>
                    if(curTaskStatue.equals("已完成")) {

                        System.out.println("当前firstIndex:===>" + HisTory.firstIndex + ",i===>" + i);
                        taskName = farr[i].split(":")[0];
                        SuperMarketFirstClass.curFirstName = taskName; //一级分类名称

                        //删除一级分类类目
                        Object o = new Object();
                        for (int k = 0; k < appPois.length; k++) {
                            String tname = taskName;
                            String appPoiId = appPois[k];
                            new Thread(new Runnable() {
                                @SneakyThrows
                                @Override
                                public void run() {
                                    synchronized (o) {
                                        BatchDelete(tname, appPoiId, false);
                                    }
                                }
                            }).start();
                            try {
                                TimeUnit.MILLISECONDS.sleep(200);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        //要等待上面删除店铺分类，返回结果
                        try {
                            System.out.println("正在等待店铺分类删除ing...............");
                            TimeUnit.MILLISECONDS.sleep(storeIds.split(",").length * 500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    //删除一级分类<<End>>
                    TimeUnit.MILLISECONDS.sleep(2000);

                    pointX=Integer.valueOf(farr[i].split(":")[1]);
                    pointY=Integer.valueOf(farr[i].split(":")[2]);
                    System.out.println("第一级点击分类:"+taskName);

                    //移动窗体到左上角0,0
                    //移动窗体并点击分类<<Start>>
                    try {

                        //生成二级菜单->美团和数组，并保存到数据库

                        //*****************************
                        //while循环等级二级菜单生成（等待点击一级分类）
                        //*****************************
                        System.out.println("当前任务状态"+curTaskStatue);
                        if(curTaskStatue.equals("进行中")){
                            //赋值给二级分类ch
                            SuperMarketSecondClass.secondArr=DataSourceConfig.GetSecondArrsById(HisTory.curTaskId).split(",");
                            System.out.println("任务进行中...还原赋值继续进行！！！........");
                            System.out.println("【数组内容】111");
                            System.out.println(Arrays.toString(SuperMarketSecondClass.secondArr));
                        }else{
                            HisTory.secondIndex=0;
                            //DataSourceConfig.UpdateStatusById(HisTory.curTaskId,"已完成");
                            while(true) {
                                if(SuperMarketSecondClass.secondArr.length > 0) break;
                                System.out.println("请点击一级菜单【"+taskName+"】获取动态二级最新菜单...");
                                try {TimeUnit.MILLISECONDS.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
                            }
                            System.out.println("检查到数组有值了...");
                            System.out.println("准备更新的二级分类数组");
                            System.out.println(ArrayUtils.toString(SuperMarketSecondClass.secondArr,"").replace("{","").replace("}",""));
                            //更新数组到数据库
                            if(HisTory.curTaskId!=-1){
                                DataSourceConfig.UpdateSecondArrsById(HisTory.curTaskId,ArrayUtils.toString(SuperMarketSecondClass.secondArr,"").replace("{","").replace("}",""));
                                DataSourceConfig.UpdateStatusById(HisTory.curTaskId, "进行中");
                            }
                        }




                        //*****************************
                        //批量更新/创建店铺二级分类
                        //*****************************
                        if(curTaskStatue.equals("已完成")) {
                            //记录当前二级分类数组到数据库
                            //数组转字符串
                            /*String[] tests=new String[]{"null", "火锅季:50:305:yd02","null" ,"品质肉店:50:405:yd04" ,"牛羊肉:50:455:yd05" };
                            System.out.println(ArrayUtils.toString(tests,"").replace("{","").replace("}",""));*/
                            /*if(HisTory.curTaskId!=-1){
                                DataSourceConfig.UpdateSecondArrsById(HisTory.curTaskId,ArrayUtils.toString(SuperMarketSecondClass.secondArr,"").replace("{","").replace("}",""));
                            }*/
                            Object pp = new Object();
                            for (int m = 0; m < appPois.length; m++) {
                                String appPoiId = appPois[m];
                                String tname = taskName; //确定最终值才能在多线程里使用
                                String num = String.valueOf(m);
                                new Thread(new Runnable() {
                                    @SneakyThrows
                                    @Override
                                    public void run() {
                                        synchronized (pp) {
                                            System.out.println("【批量更新/创建店铺二级分类】启动批量更新线程" + num);
                                            doWork.CreateMeiTuanClass(tname, appPoiId); //创建一级分类和二级分类
                                        }
                                    }
                                }).start();
                                try {
                                    TimeUnit.MILLISECONDS.sleep(50);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                            //要等待上面创建分类，返回结果
                            System.out.println("等待" + (storeIds.split(",").length * 3000) + "秒，创建分类...");
                            try {
                                TimeUnit.MILLISECONDS.sleep(storeIds.split(",").length * 1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }

                        System.out.println("二级菜单创建完成......");
                        isStartWork=false;
                        isSameClick = 0; //复位
                        ClickIdsList.clear(); //清空点击记录

                        System.out.println("【数组内容】222");
                        System.out.println(Arrays.toString(SuperMarketSecondClass.secondArr));


                        //更新用户状态
                        DataSourceConfig.UpdateStatusById(HisTory.curTaskId,"进行中");
                        try {TimeUnit.MILLISECONDS.sleep(200);} catch (InterruptedException e) {e.printStackTrace();}
                        System.out.println("开始操作");
                        System.out.println("当前二级索引"+HisTory.secondIndex);
                        System.out.println("数组长度333："+SuperMarketSecondClass.secondArr.length);

                        //*****************************
                        //开始循环点击二级菜单
                        //*****************************
                        for (int j = HisTory.secondIndex; j < SuperMarketSecondClass.secondArr.length-1; j++) {

                            /*if(j==0){
                                isSameClick=0; //复位
                                ClickIdsList.clear(); //清空点击记录
                            }
                            */
                            /*if(j>SuperMarketSecondClass.secondArr.length-1){ //最最后的一个分类，不在界面显示中，无法点击获取，所以要跳出
                                System.out.println("最后一个分类,跳出j二级循环......");
                                break;
                            }*/

                            ClickIdsList.clear();
                            if (SuperMarketSecondClass.secondArr[j] == null || SuperMarketSecondClass.secondArr[j].equals("null") ) continue;
                            //System.out.println(SuperMarketSecondClass.secondArr[j] == "null");


                            //记录当前一、二级循环索引
                            //############################################
                            String secondarrays=ArrayUtils.toString(SuperMarketSecondClass.secondArr,"").replace("{","").replace("}","");
                            System.out.println("setTaskHistory字段值："+HisTory.curTaskId+","+firstIndex+","+j+","+taskName);
                            DataSourceConfig.setTaskHistory(HisTory.curTaskId,firstIndex,j,taskName,secondarrays);
                            //###########################################


                            String[] Temp = SuperMarketSecondClass.secondArr[j].split(":");
                            pointX = Integer.valueOf(Temp[1]);
                            pointY = Integer.valueOf(Temp[2]);
                            classCode = Temp[3];
                            HisTory.classCode = classCode;
                            System.out.println("上传的分类code===>"+classCode+","+HisTory.classCode);

                            //移动到左侧菜单列表
                            AutoRobot.MouseMove(robot, pointX, pointY);
                            robot.delay(500);

                            //滚动往上
                            if (Line == false) {
                                robot.mouseWheel(-200);
                                robot.delay(500);
                            } else {
                                robot.mouseWheel(200);
                                robot.delay(500);
                            }

                            if (Temp.length == 5) {
                                System.out.println("鼠标滑动...");
                                Line = true; //换行
                            }

                            System.out.println("J循环里的点击，左侧菜单...");
                            AutoRobot.MouseClick(robot);
                            robot.delay(500);

                            /*System.out.println("程序终止退出..........");
                            System.exit(0);*/

                            int loop =8; //循环列表次数
                            while (loop > 0) {

                                if (isSameClick > 5) { //连续3次相同,到底部了,跳到下一个分类
                                    System.out.println("连续5次相同,到底部了,跳到下一个分类");
                                    isSameClick = 0; //跳到下一个分类
                                    isStartWork=false;
                                    break;
                                }

                                System.out.println("******************************************");
                                System.out.println("菜单列表点击..."+loop);
                                System.out.println("******************************************");

                                //第一次点击
                                AutoRobot.MouseMove(robot, 150, 320); //移动到菜单列表
                                robot.delay(delay500);
                                AutoRobot.MouseClick(robot);
                                robot.delay(delay500);
                                AutoRobot.MouseMove(robot, 20, 20); //移动到左上角返回 20,20
                                robot.delay(delay500);
                                AutoRobot.MouseClick(robot);
                                robot.delay(delay100);

                                //第二次点击
                                AutoRobot.MouseMove(robot, 150, 380); //移动到左上角返回
                                robot.delay(delay500);
                                AutoRobot.MouseClick(robot);
                                robot.delay(delay500);
                                AutoRobot.MouseMove(robot, 20, 20); //移动到左上角返回  20,20
                                robot.delay(delay500);
                                AutoRobot.MouseClick(robot);
                                robot.delay(delay100);

                                //第三次点击
                                AutoRobot.MouseMove(robot, 150, 470); //移动到左上角返回
                                robot.delay(delay500);
                                AutoRobot.MouseClick(robot);
                                robot.delay(delay500);
                                AutoRobot.MouseMove(robot, 20, 20); //移动到菜单列表  20,20
                                robot.delay(delay500);
                                AutoRobot.MouseClick(robot);
                                robot.delay(delay100);

                                //第四次点击
                                AutoRobot.MouseMove(robot, 150, 580); //移动到菜单列表
                                robot.delay(delay500);
                                AutoRobot.MouseClick(robot);
                                robot.delay(delay500);
                                AutoRobot.MouseMove(robot, 20, 20); //移动到菜单列表 20,20
                                robot.delay(delay500);
                                AutoRobot.MouseClick(robot);
                                robot.delay(delay100);

                                //第五次点击
                                AutoRobot.MouseMove(robot, 150, 680); //移动到菜单列表
                                robot.delay(delay500);
                                AutoRobot.MouseClick(robot);
                                robot.delay(delay500);
                                AutoRobot.MouseMove(robot, 20, 20); //移动到菜单列表 20,20
                                robot.delay(delay500);
                                AutoRobot.MouseClick(robot);
                                robot.delay(delay100);

                                System.out.println("##########################################");
                                System.out.println("在这里循环滚动鼠标中伦..." + loop);
                                System.out.println("##########################################");

                                AutoRobot.MouseMove(robot, 270, 500); //移动到菜单列表
                                robot.delay(delay500);
                                //滑动页面4次
                                robot.mouseWheel(4);

                                //Point point=AutoRobot.FindTargetImagePositon(robot,"收起.png");
                                //这里要设置1000（1秒）否则可能点击不同步
                                try {
                                    TimeUnit.MILLISECONDS.sleep(2000);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                loop--;

                            } // while End */


                            //记录二维数组菜单+1
                            //############################################
                            System.out.println("记录二维数组菜单+1...");
                            secondarrays=ArrayUtils.toString(SuperMarketSecondClass.secondArr,"").replace("{","").replace("}","");
                            DataSourceConfig.setTaskHistory(HisTory.curTaskId,firstIndex,j+1,taskName,secondarrays);
                            //###########################################


                            //到了二级最后一个分类<<Start>>
                            System.out.println("......=结算=......"+(j+1));

                            if((j+1)>=SuperMarketSecondClass.secondArr.length-1){
                                System.out.println("......二级最后一分类......");
                                DataSourceConfig.UpdateStatusById(HisTory.curTaskId,"已完成");
                                System.out.println("当前二级分类:"+HisTory.secondIndex);
                                System.out.println("当前数组长度:"+SuperMarketSecondClass.secondArr.length);
                                //备份上次的任务
                                System.out.println("备份上次的任务......");
                                Backupsupermarketoldtask backup=new Backupsupermarketoldtask();
                                backup.setTaskfirst(i);
                                backup.setTaskname(taskName);
                                backup.setTasksecond(HisTory.secondIndex);
                                backup.setSecondarrays(secondarrays);
                                System.out.println("备份的素组"+secondarrays);
                                DataSourceConfig.backupOldTask(HisTory.curTaskId,backup); //保存上次任务

                                System.out.println("更新新的任务......");
                                Curtaskforsupermarket taskData=new Curtaskforsupermarket();
                                int newIndex=i+1;
                                taskData.setId(HisTory.curTaskId);
                                taskData.setTaskname(farr[newIndex].split(":")[0]);
                                taskData.setTaskfirst(newIndex);
                                taskData.setTasksecond(0);
                                taskData.setSecondarrays(secondarrays);
                                taskData.setStatus("已完成");
                                DataSourceConfig.setCurTask(HisTory.curTaskId,taskData); //更新新的一级任务

                            } //到了二级最后一个分类<<End>>


                            //*****************************
                            //重新进入小程序，释放内存
                            //*****************************
                            isReStartProgram=true;
                            int restartStatus=RestartProgram(robot,isReStartProgram);
                            if(restartStatus==1){
                                isBreakFirstFor=true; //终止for循环
                                Robot rb=new Robot();
                                TimerTask task=new TimerTask() {
                                    @SneakyThrows
                                    @Override
                                    public void run() {
                                        isReStartProgram=false;
                                        isBreakFirstFor=false;
                                        //清空变量
                                        dataMapList.clear();
                                        startDoTask(rb);
                                    }
                                };
                                Timer timer=new Timer();
                                timer.schedule(task,3000);
                                System.out.println("3秒后，重启任务");
                                break;
                            }

                            //记录二级分类索引
                            HisTory.secondIndex=j;

                        } // for J End

                    } catch (Exception e) {
                        e.printStackTrace();
                        System.out.println("woWork移动窗体发生错误");
                    }
                    //移动窗体并点击分类<<End>>

                    if(isBreakFirstFor){
                        System.out.println("重新进入小程序,停止for循环");
                        break;
                    }

                } //for i End

            }
        }catch (Exception ex){
            System.out.println("发生错误111:"+ex.getMessage());
        } //try End
    }




    /*
     *  重新进入小程序
     * */
    public static int RestartProgram(Robot robot,Boolean isReStart) throws Exception {
        if(!isReStart) return 0;
        try {
            WinDef.HWND handle = AutoRobot.getWindowHandle("Chrome_WidgetWin_0", "沃尔玛");
            System.out.println("handle:===>" + handle);
            if (handle != null) {
                //移动窗体
                AutoRobot.moveWindowHandle(handle, 0, 0, 415, 780, false);
                TimeUnit.MILLISECONDS.sleep(200);
                //鼠标移动到选项，准备点击小程序
                AutoRobot.MouseMove(robot,308,20);
                robot.delay(500);
                AutoRobot.MouseClick(robot);
                robot.delay(500);
                //点击重新进入小程序
                AutoRobot.MouseMove(robot,175,270);
                robot.delay(500);
                AutoRobot.MouseClick(robot);
                robot.delay(500);

                return 1; //重新启动
            }
        }catch (Exception ex){
            System.out.println("重新进入小程序发生错误："+ex.getMessage());
        }

        return 0;
    }



    /*
    *  创建分类
    * */
    public static int CreateMeiTuanClass(String taskName,String appPoiCode) throws Exception {
        if(SuperMarketSecondClass.secondArr.length<=0) return -1;
        //创建分类
        StringBuilder sb=new StringBuilder();
        for (int k = 0; k < SuperMarketSecondClass.secondArr.length; k++) {
            /*if(k==0){
                isSecondMode=false; //创建一级分类
                System.out.println("创建一级分类。。。");
            }else{
                isSecondMode=true; //创建二级分类
                System.out.println("创建二级分类。。。");
            }*/
            String singleData = SuperMarketSecondClass.secondArr[k].replaceAll("\\s*", ""); //冬日火锅:50:355:ny03);
            if (singleData.equals("null")) {
                isSecondMode=false; //创建一级分类
                continue;
            }
            String firstName = taskName;//一级分类
            String secondName = singleData.split(":")[0];
            String secondCode = singleData.split(":")[3];
            //重新创建分类
            String res = MeiTuan_CreateItem(appPoiCode,firstName, isSecondMode, secondName, secondCode); //创建一级分类和二级分类
            isSecondMode=true;
            /*System.out.println("创建分类类结果:");
            System.out.println(res);*/
            sb.append("firstName:"+firstName+":"+secondName+":"+secondCode+"\n");
            System.out.println("分类集合:");
            System.out.println(sb.toString());
            try {
                TimeUnit.MILLISECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        isSecondMode=false;
        return 0;
    }




    private static void Check(Robot robot) throws Exception {
        try{
            Point pointtest=AutoRobot.FindTargetImagePositon(robot,"w1.png");
            if(pointtest.x!=-1 && pointtest.y!=-1){
                throw new Exception("首页wer1..停止循环");
            }
            pointtest=AutoRobot.FindTargetImagePositon(robot,"w2.png");
            if(pointtest.x!=-1 && pointtest.y!=-1){
                throw new Exception("首页wer2..停止循环");
            }
            pointtest=AutoRobot.FindTargetImagePositon(robot,"w3.png");
            if(pointtest.x!=-1 && pointtest.y!=-1){
                throw new Exception("购物车w1car..停止循环");
            }
        }catch (Exception ex){}
    }



    /**
     * 过滤敏感词
     * */
    public static String filterWord(String inputString){
        String[] words=new String[]{"礼券","首选","京东","自营","京豆","沃尔玛","首选","独家","软蓝","TOP1","元","包邮","热销爆款","热销","爆款","云硬","限时","终极","直播间","冠军","到手价","价","液化气","套刀"};
        String target = inputString;
        boolean found = false;
        for (String s : words) {
            if (target.indexOf(s)!=-1) {
                target=target.replace(s,"");
                return filterWord(target);
            }
        }
        return target;
    }


    /**
     * 获取商品信息
     * */
    /*public static void getProductInfo(String ResponseMessage){
        //转换格式为json
        JSONObject jsonObject = JSONObject.parseObject(ResponseMessage);
        JsonParser.traverseJson(jsonObject);
        try { TimeUnit.MILLISECONDS.sleep( 200); } catch (InterruptedException e) { e.printStackTrace(); }
        //遍历对象
        Map<String,Object> getAllJsonObject=JsonParser.getAllJsonObject;
        System.out.println("pageList商品列表信息");
        System.out.println(getAllJsonObject.get("pageList"));
        //列表数据
        JSONArray pageList= (JSONArray) getAllJsonObject.get("pageList");
        *//* 遍历JSONArray数组 *//*
        if(pageList.size()>0){
            for (int i = 0; i < pageList.size(); i++) {
                JSONObject obj = pageList.getJSONObject(i);
                //产品skuid
                String wid= obj.getString("id").toString();
                System.out.println("产品skuid:"+wid);
                //产品图片
                String pimg = obj.getString("defultImageUrl").toString().replace("!q70.dpg","");
                System.out.println("产品图片:"+pimg);

                //产品名称
                String pname =doWork.filterWord(obj.getString("title").toString());
                System.out.println("产品名称:"+pname);
                //产品名称 长度不能大于45
                if(pname.length()>45){
                    pname=pname.substring(0,35)+Tools.generateCode5()+"...";  //加上随机五位验证码
                }else{
                    pname=pname+Tools.generateCode5(); //加上随机五位验证码
                    if(pname.length()>45){
                        pname=pname.substring(0,43);
                    }
                }
                //产品价格
                String price = obj.getString("minSalePrice").toString();
                System.out.println("价格:"+price);

                System.out.println("========================================");
            }
        }
    }*/


    /**
     * 获取商品信息  -- 多店
     **/
    public static void getProductInfoForMultiStore(String ResponseMessage) throws Exception {

        //转换格式为json
        JSONObject jsonObject = JSONObject.parseObject(ResponseMessage);
        JsonParser.traverseJson(jsonObject);
        //try { TimeUnit.MILLISECONDS.sleep( 30); } catch (InterruptedException e) { e.printStackTrace(); }
        String brandName="自营";
        long TagId=200002538L;


        //系统默认参数
        SystemParam systemParam=new SystemParam();
        //遍历对象
        Map<String,Object> getAllJsonObject=JsonParser.getAllJsonObject;
        //整体对象
        JSONObject topGoods= JSON.parseObject(getAllJsonObject.get("data").toString());
        JSONObject goodsObj =JSONObject.parseObject(topGoods.get("goods").toString()); //取顶级goods对象，防止相同名
        //System.out.println("skuCode是否为空..."+goodsObj);

        //商品id循环:app_poi_code=18665261
        String goodsid=goodsObj.get("id").toString();

        System.out.println("当前商品id"+goodsid);

        if(ClickIdsList.contains(goodsid)){
            System.out.println("此商品已抓取过....................跳过");
            isSameClick++;
            return;
        }
        ClickIdsList.add(goodsid);
        if(isSameClick>0) isSameClick--;

        String skuCode=goodsObj.get("outerGoodsCode").toString();

        //标题
        String goodsTitle="【伟星_商超_批量更新_测试】"+filterWord(goodsObj.get("title").toString());
        if(goodsTitle.length()>=42) goodsTitle=goodsTitle.substring(0,42)+"..";

        //描述/卖点
        String goodsSellingPoint=goodsObj.get("goodsSellingPoint").toString();
        //价格
        String minOriginalPrice=goodsObj.get("minSalePrice").toString();
        //封面图
        String defultImageUrl=goodsObj.get("defultImageUrl").toString();

        //产品多图，放进详情图
        //详情图
        StringBuilder DetailImagesList=new StringBuilder();
        JSONArray imagesList= (JSONArray) getAllJsonObject.get("goodsImageUrl");
        //* 遍历JSONArray数组 *//*
        if(imagesList.size()>0){
            for (int i = 0; i < imagesList.size(); i++) {
                String singleImage = imagesList.get(i).toString();
                byte[] singleImgData= ImageDownLoader.getImageBytes(singleImage);
                UploadImageAPI uploadImageAPI=new UploadImageAPI();
                uploadImageAPI.setImg_data(singleImgData);
                String imgName=FileUtils.extractFileNameFromUr1(singleImage);
                uploadImageAPI.setImg_name(imgName);
                //设置时间戳
                uploadImageAPI.setTimestamp(System.currentTimeMillis());
                //设置签名
                uploadImageAPI.setSignValue(uploadImageAPI.getSign());
                //调用方法
                String uploadImageId=uploadImageAPI.uploadImage();
                //System.out.println("图片上传id:===>"+uploadImageId);
                //保存上传的每一张图片集合
                DetailImagesList.append(uploadImageId+","); //"AA,BB" 上传接口的图片id
                //等待图片上传
                try { TimeUnit.MILLISECONDS.sleep( 50); } catch (InterruptedException e) { e.printStackTrace(); }
                System.out.println("标题:"+goodsTitle);
                System.out.println("描述/卖点:"+goodsSellingPoint);
                System.out.println("价格:"+minOriginalPrice);
                System.out.println("封面图:"+defultImageUrl);
                System.out.println("产品图片:"+singleImage);
                System.out.println("========================================");
            }
        } //if end

        //多点上传类
        MultiPois multiPois=new MultiPois();

        //设置 App_poi_code 属性
        //设置多门店
        multiPois.setApp_poi_codes(storeIds); //获取门店id
        multiPois.setApp_spu_code(skuCode); //APP方商品id
        multiPois.setName(goodsTitle); //商品名称
        multiPois.setTag_id(TagId); //类目id
        multiPois.setCategory_code_list("[\""+HisTory.classCode+"\"]"); //示例值: ["1111","2222"]

        //图片ids
        String[] surfacePhoto=DetailImagesList.toString().split(",");
        if(surfacePhoto.length>=4){
            multiPois.setPicture(surfacePhoto[0]+","+surfacePhoto[1]+","+surfacePhoto[2]); //传3张封面图 -- 默认不取第一张，有水印和自营
        }else{
            if(surfacePhoto.length<=1){
                multiPois.setPicture(surfacePhoto[0]); //传3张封面图 -- 默认不取第一张，有水印和自营
            }else{
                if(surfacePhoto.length<4) {
                    multiPois.setPicture(surfacePhoto[0] + "," + surfacePhoto[1] + "," + surfacePhoto[2]); //传3张封面图 -- 默认不取第一张，有水印和自营
                }else{
                    multiPois.setPicture(surfacePhoto[0]);
                }
            }
        }

        //产品详情图
        multiPois.setPicture_contents(DetailImagesList.toString().substring(0,DetailImagesList.toString().length()-1)); //去除最后一个逗号

        //sku信息
        ArrayList<MultiPois.skusObjects> skuList=new ArrayList<>();
        //添加sku库存信息
        JSONArray properArr= (JSONArray) goodsObj.get("goodsPropertyList");

        //产品规格 -- 口感
        ArrayList<String> feels=new ArrayList<>();

        //循环取值
        for (int i = 0; i < properArr.size(); i++) {
            JSONObject obj = properArr.getJSONObject(i);
            String sname=obj.getString("value");
            if(sname.length()>20) sname=sname.substring(0,20);
            feels.add(sname);
        }

        if(feels.size()>0){
            for (int i = 0; i < feels.size(); i++) {
                MultiPois.skusObjects skusObjects=new MultiPois.skusObjects();
                skusObjects.setStock("30"); //设置库存
                skusObjects.setWeight_for_unit("30");
                skusObjects.setWeight_unit("千克(kg)");
                skusObjects.setUpc("no_upc");
                skusObjects.setSku_id(String.valueOf(System.currentTimeMillis())+Tools.generateCode4());
                String specName=feels.get(i).replace("[","【").replace("]","】")+Tools.generateCode2();
                if(specName.length()>20) specName=specName.substring(0,20);
                skusObjects.setSpec(filterWord(specName));
                skusObjects.setPrice(minOriginalPrice); //如果没传sku，则该字段必填
                skuList.add(skusObjects);
            }
        }


        if(skuList.size()<=0){
            MultiPois.skusObjects skusObjects=new MultiPois.skusObjects();
            skusObjects.setStock("30"); //设置库存
            skusObjects.setWeight_for_unit("30");
            skusObjects.setWeight_unit("千克(kg)");
            skusObjects.setStock("30");
            skusObjects.setUpc("no_upc"); //特殊字段逻辑： 1.新增或更新商品时如无upc字段则可传"no_upc"，跳过校验。
            skusObjects.setSku_id(String.valueOf(System.currentTimeMillis())+Tools.generateCode4());
            String specName="默认"+Tools.generateCode2();
            if(specName.length()>20) specName=specName.substring(0,20);
            skusObjects.setSpec(filterWord(specName));
            skusObjects.setPrice(minOriginalPrice); //如果没传sku，则该字段必填
            skuList.add(skusObjects);
        }

        System.out.println("======打印skuList======");
        skuList.forEach(System.out::println);

        multiPois.setSkus(skuList); //设置sku信息

        //设置普通属性
        saleByTagIdAPI commByTagIdapi=new saleByTagIdAPI();
        commByTagIdapi.setTimestamp(System.currentTimeMillis());
        commByTagIdapi.setTag_id(TagId);
        //System.out.println(tagId.getSign());
        commByTagIdapi.setSignValue(commByTagIdapi.getSign());
        String commRes=commByTagIdapi.getClassFromTagId();
        //System.out.println("获取Tag_id类目结果......");
        //System.out.println(commRes);
        List<MeituanGoods.fooddata.commonAttrClass> commList=saleByTagIdAPI.convertCommonAttrObj(commRes,brandName);
        try { TimeUnit.MILLISECONDS.sleep( 50); } catch (InterruptedException e) { e.printStackTrace(); }

        //添加公共属性
        multiPois.setCommon_attr_value(commList);

        //添加限购信息
        String limit_sale_info="{\"limitSale\":false}";
        multiPois.setLimit_sale_info(limit_sale_info);

        //发送请求
        multiPois.setTimestamp(System.currentTimeMillis());
        multiPois.setSignValue(multiPois.getSign()); //设置签名


        System.out.println("打印类>>>>>>>>>>>>>>>>>>>>>>");
        System.out.println(JSON.toJSONString(multiPois)+"666666666666");

        String res=multiPois.startMulitPois();

        System.out.println();
        System.out.println("程序到了最后");


    } //多店end










    /**
     * 获取商品信息  -- 单店
     * */
    public static void getProductInfo(String ResponseMessage) throws Exception {

        //转换格式为json
        JSONObject jsonObject = JSONObject.parseObject(ResponseMessage);
        JsonParser.traverseJson(jsonObject);
        try { TimeUnit.MILLISECONDS.sleep( 200); } catch (InterruptedException e) { e.printStackTrace(); }

        String brandName="自营";
        long TagId=200002727L;
        //String classCode="fd01";
        String classCode=HisTory.classCode;
        System.out.println("当前美团分类上传code.."+classCode);

        //系统默认参数
        SystemParam systemParam=new SystemParam();

        //遍历对象
        Map<String,Object> getAllJsonObject=JsonParser.getAllJsonObject;
        //整体对象
        JSONObject topGoods= JSON.parseObject(getAllJsonObject.get("data").toString());
        JSONObject goodsObj =JSONObject.parseObject(topGoods.get("goods").toString()); //取顶级goods对象，防止相同名
        //System.out.println("skuCode是否为空..."+goodsObj);

        //商品id循环:app_poi_code=18665261
        String goodsid=goodsObj.get("id").toString();

        if(ClickIdsList.contains(goodsid)){
            System.out.println("此商品已抓取过....................跳过");
            isSameClick++;
            return;
        }
        ClickIdsList.add(goodsid);
        if(isSameClick>0) isSameClick--;

        //skucode
        String skuCode=goodsObj.get("outerGoodsCode").toString();

        //标题
        String goodsTitle=filterWord(goodsObj.get("title").toString());
        if(goodsTitle.length()>=42) goodsTitle=goodsTitle.substring(0,42)+"..";

        //描述/卖点
        String goodsSellingPoint=goodsObj.get("goodsSellingPoint").toString();
        //价格
        String minOriginalPrice=goodsObj.get("minSalePrice").toString();
        //封面图
        String defultImageUrl=goodsObj.get("defultImageUrl").toString();

        //产品多图，放进详情图
        //详情图
        StringBuilder DetailImagesList=new StringBuilder();
        JSONArray imagesList= (JSONArray) getAllJsonObject.get("goodsImageUrl");
        //* 遍历JSONArray数组 *//*
        if(imagesList.size()>0){
            for (int i = 0; i < imagesList.size(); i++) {
                String singleImage = imagesList.get(i).toString();
                byte[] singleImgData= ImageDownLoader.getImageBytes(singleImage);
                UploadImageAPI uploadImageAPI=new UploadImageAPI();
                uploadImageAPI.setImg_data(singleImgData);
                String imgName=FileUtils.extractFileNameFromUr1(singleImage);
                uploadImageAPI.setImg_name(imgName);
                //设置时间戳
                uploadImageAPI.setTimestamp(System.currentTimeMillis());
                //设置签名
                uploadImageAPI.setSignValue(uploadImageAPI.getSign());
                //调用方法
                String uploadImageId=uploadImageAPI.uploadImage();
                //System.out.println("图片上传id:===>"+uploadImageId);
                //保存上传的每一张图片集合
                DetailImagesList.append(uploadImageId+","); //"AA,BB" 上传接口的图片id
                //等待图片上传
                try { TimeUnit.MILLISECONDS.sleep( 200); } catch (InterruptedException e) { e.printStackTrace(); }
                System.out.println("标题:"+goodsTitle);
                System.out.println("描述/卖点:"+goodsSellingPoint);
                System.out.println("价格:"+minOriginalPrice);
                System.out.println("封面图:"+defultImageUrl);
                System.out.println("产品图片:"+singleImage);
                System.out.println("========================================");
            }
        } //if end

        //产品类
        MeituanGoods goods=new MeituanGoods();

        //设置 App_poi_code 属性
        goods.setApp_poi_code(systemParam.getApp_poi_code()); //获取门店id

        //设置 food_data 属性
        MeituanGoods.fooddata foodData=new MeituanGoods.fooddata();
        foodData.setApp_spu_code(skuCode);
        foodData.setName(goodsTitle);
        foodData.setPrice(Float.valueOf(minOriginalPrice)); //如果没传sku，则该字段必填
        foodData.setUnit("个");
        foodData.setTag_id(TagId); //数码家电,手机配件,手机充电器 (美团后台类目)

        String[] surfacePhoto=DetailImagesList.toString().split(",");
        if(surfacePhoto.length>=4){
            foodData.setPicture(surfacePhoto[0]+","+surfacePhoto[1]+","+surfacePhoto[2]); //传3张封面图 -- 默认不取第一张，有水印和自营
        }else{
            if(surfacePhoto.length<=1){
                foodData.setPicture(surfacePhoto[0]); //传3张封面图 -- 默认不取第一张，有水印和自营
            }else{
                if(surfacePhoto.length<4) {
                    foodData.setPicture(surfacePhoto[0] + "," + surfacePhoto[1] + "," + surfacePhoto[2]); //传3张封面图 -- 默认不取第一张，有水印和自营
                }else{
                    foodData.setPicture(surfacePhoto[0]);
                }
            }
        }

        //产品详情图
        foodData.setPicture_contents(DetailImagesList.toString().substring(0,DetailImagesList.toString().length()-1)); //去除最后一个逗号


        //设置一级分类
        //设置分类信息
        //foodData.setCategory_name("数码家电");

        //指定二级分类同步更新
        //1、先查询api获取创建的分类id
        //2、 设置分类id category_code
        //上传商品到指定二级分类
        foodData.setCategory_code(classCode);

        //设置上架状态
        //商品上下架状态，字段取值范围：0-上架，1-下架。
        // 创建商品时，本参数如传的不是0,1或不传，则默认为下架状态。
        foodData.setIs_sold_out(0); //默认上架

        //sku信息
        ArrayList<MeituanGoods.fooddata.skusObjects> skuList=new ArrayList<>();

        //添加sku库存信息
        JSONArray properArr= (JSONArray) goodsObj.get("goodsPropertyList");
        //产品规格 -- 口感
        ArrayList<String> feels=new ArrayList<>();

        //循环取值
        for (int i = 0; i < properArr.size(); i++) {
            JSONObject obj = properArr.getJSONObject(i);
            String sname=obj.getString("value");
            if(sname.length()>20) sname=sname.substring(0,20);
            feels.add(sname);
        }

        if(feels.size()>0){
            for (int i = 0; i < feels.size(); i++) {
                MeituanGoods.fooddata.skusObjects skusObjects=new MeituanGoods.fooddata.skusObjects();
                skusObjects.setWeight(30L);
                skusObjects.setStock("30");
                skusObjects.setUpc("no_upc");
                skusObjects.setSku_id(String.valueOf(System.currentTimeMillis()));
                String specName=feels.get(i).replace("[","【").replace("]","】")+Tools.generateCode2();
                if(specName.length()>20) specName=specName.substring(0,20);
                skusObjects.setSpec(filterWord(specName));
                skusObjects.setPrice(minOriginalPrice); //如果没传sku，则该字段必填
                skuList.add(skusObjects);
            }
        }


        if(skuList.size()<=0){
            MeituanGoods.fooddata.skusObjects skusObjects=new MeituanGoods.fooddata.skusObjects();
            skusObjects.setWeight(30L);
            skusObjects.setStock("30");
            skusObjects.setUpc("no_upc"); //特殊字段逻辑： 1.新增或更新商品时如无upc字段则可传"no_upc"，跳过校验。
            skusObjects.setSku_id(String.valueOf(System.currentTimeMillis()));
            String specName="默认"+Tools.generateCode2();
            if(specName.length()>20) specName=specName.substring(0,20);
            skusObjects.setSpec(filterWord(specName));
            skusObjects.setPrice(minOriginalPrice); //如果没传sku，则该字段必填
            skuList.add(skusObjects);
        }

        //添加到规格
        foodData.setSkus(skuList);


        //设置普通属性
        saleByTagIdAPI commByTagIdapi=new saleByTagIdAPI();
        commByTagIdapi.setTimestamp(System.currentTimeMillis());
        commByTagIdapi.setTag_id(TagId);
        //System.out.println(tagId.getSign());
        commByTagIdapi.setSignValue(commByTagIdapi.getSign());
        String commRes=commByTagIdapi.getClassFromTagId();
        //System.out.println("获取Tag_id类目结果......");
        System.out.println(commRes);
        List<MeituanGoods.fooddata.commonAttrClass> commList=saleByTagIdAPI.convertCommonAttrObj(commRes,brandName);
        try { TimeUnit.MILLISECONDS.sleep( 200); } catch (InterruptedException e) { e.printStackTrace(); }

        //添加公共属性
        foodData.setCommon_attr_value(commList);


        //设置整个类属性到FoodData属性
        //过滤字段
        JSONObject filterFoodData=JSONObject.parseObject(JSONObject.toJSONString(foodData));
        filterFoodData.remove("box_num");
        filterFoodData.remove("box_price");
        filterFoodData.remove("delivery_end_time");
        filterFoodData.remove("min_order_count");
        filterFoodData.remove("sale_type");
        filterFoodData.remove("is_single_no_delivery");
        filterFoodData.remove("delivery_time");
        filterFoodData.remove("sequence");
        filterFoodData.remove("qua_approval_date");
        filterFoodData.remove("is_show_upc_pic_contents");
        filterFoodData.remove("is_specialty");
        filterFoodData.remove("qua_effective_date");


        goods.setFood_data(JSONObject.toJSONString(filterFoodData));


        System.out.println("goods类属性======================>");
        //String foodDataString=JSONObject.toJSONString(goods).replace("\\\\\\\\\\\\","").replace("\\\\\\\\","").replace("\\\\","");
        String foodDataString=JSONObject.toJSONString(goods);
        System.out.println(foodDataString);


        MultiUpdateProduct multiUpdateProduct=new MultiUpdateProduct();
        multiUpdateProduct.setTimestamp(System.currentTimeMillis());
        String finalFoodDatas=JSON.parseObject(foodDataString).getString("food_data");
        System.out.println("设置foodData");
        System.out.println("###:"+finalFoodDatas.replace("\\\\",""));
        String fdataStr="["+finalFoodDatas.replace("\\\\","")+"]";
        //fdataStr=fdataStr.replace(":\"[",":[").replace("]\"","]").replace("\\","").replace("\"}","}");
        fdataStr=fdataStr.replaceAll(":\"\\s*\\[",":[").replaceAll("]\"","]").replace("\\","").replace("]\",","],");
        fdataStr=fdataStr.replaceAll("\"values\":\"\\[","\"values\":[").replace("]\"}","]}");
        System.out.println("fdataStr######################");
        //System.out.println(fdataStr.replace(" ","+"));
        fdataStr=fdataStr.replaceAll(" ","+");
        fdataStr=fdataStr.replaceAll("%","");
        multiUpdateProduct.setFood_data(fdataStr);
        multiUpdateProduct.setSignValue(multiUpdateProduct.getSign());

        String res=multiUpdateProduct.startMulitCreate();

    } //方法end











    //***************************************************************
    //饿了么商品抓取
    /**
     * 获取头部headers信息
     * */
    public static Map<String,String> catchHeaders(String HeadersMessage) throws UnsupportedEncodingException {
        return SpiderTools.getHeaders(HeadersMessage);
    }








    /*判断某值是否存在数组里*/
    public static boolean checkArrayValue(String[] arr,String tartgetValue){
        for(String s:arr){
            if(s.indexOf(tartgetValue)!=-1){
                return true;
            }
        }
        return false;
    }

    /*获取菜单*/
    public static void getItem(String ResponseMessage) throws Exception {
        dataMapList.clear();
        SuperMarketSecondClass.secondArr =new String[]{};
        if(isStartWork==false){
            //转换格式为json
            JSONObject jsonObject = JSONObject.parseObject(ResponseMessage);
            JsonParser.traverseJson(jsonObject);
            try { TimeUnit.MILLISECONDS.sleep( 200); } catch (InterruptedException e) { e.printStackTrace(); }
            //遍历对象
            Map<String,Object> getAllJsonObject=JsonParser.getAllJsonObject;

            //StringBuilder DetailImagesList=new StringBuilder();
            JSONArray itemsList= (JSONArray) getAllJsonObject.get("classifyList");

            String parentId=JSONObject.parseObject(getAllJsonObject.get("data").toString()).get("goodsClassifyId").toString(); //=> 1479400142
            String parentName=""; //1479400142=>水果蔬菜
            String parentCode=""; //水果蔬菜=》fd
            if(!StringUtils.isEmpty(parentId)){
                parentName=SuperMarketFirstClass.getClassName(Integer.valueOf(parentId)); //1479400142=>水果蔬菜
                //SuperMarketFirstClass.curFirstName=parentName; //公共变量（一级分类）
                parentCode=SuperMarketFirstClass.getCode(parentName); //水果蔬菜=》fd
            }


            Boolean isCreateFirstClass=true; //是否已创建一级分类

            int num=0;
            int Ypos=0;
            for (int i = 0; i < itemsList.size(); i++) {
                JSONObject obj =JSONObject.parseObject(itemsList.get(i).toString());
                String EnterLine="";
                if(i<=9){
                    Ypos=(255+i*50);
                }
                if(i==9){
                    EnterLine=":Enter";
                }
                if(i>9){
                    Ypos=750-(itemsList.size()-9)*50; //换行后的起始位置
                    if((itemsList.size()-9)==1){ // 10-9===1
                        Ypos=708;
                    }else{
                        Ypos+=num*50+100;
                        num++;
                    }
                }
                String title=obj.getString("title");
                //System.out.println("名称:"+title+",x坐标:50,y坐标:"+Ypos+EnterLine);
                generatetemMap(i,parentCode,title,"50",String.valueOf(Ypos));
                //System.out.println("=================   换行起始位置:"+Ypos+"   ===================");
            } //for End
            String[] secondArr=dataMapList.toArray(new String[dataMapList.size()]);
            System.out.println("==========转换地图1:==========");
            SuperMarketSecondClass.secondArr=secondArr.clone(); //公共变量（二级分类）
            System.out.println("是否同一个数组:"+(SuperMarketSecondClass.secondArr==secondArr));
            System.out.println(Arrays.toString(secondArr));

            //检查数组里是否包含指定的二级分类
            /*boolean isArrValue=checkArrayValue(secondArr,secondDefined); //secondDefined是二级分类指定查找的值
            if(isArrValue) {
                System.out.println("==========转换地图1:==========");
                SuperMarketSecondClass.secondArr = secondArr.clone(); //公共变量（二级分类）
                System.out.println("是否同一个数组:" + (SuperMarketSecondClass.secondArr == secondArr));
                System.out.println(Arrays.toString(secondArr));
                System.out.println("一级分类地图打印.....");
                dataMapList.forEach(System.out::println);
                dataMapList.clear(); //清空临时地图数据
            }else{
                SuperMarketSecondClass.secondArr =new String[]{};
                dataMapList.clear(); //清空临时地图数据
                System.out.println("非当前【"+parentName+"】的二级分类");
                System.out.println("【数组内容】");
                System.out.println(Arrays.toString(SuperMarketSecondClass.secondArr));
            }*/
            /*
            System.out.println("==========转换地图2===>更新到美团类目:==========");
            Boolean isSecondMode=false; //开启逐个创建二级分类
            for (int i = 0; i < secondArr.length; i++) {
                String singleData=secondArr[i].replaceAll("\\s*",""); //冬日火锅:50:355:ny03
                System.out.println("singleData单值:====>"+singleData);
                if(singleData.equals("null")){
                    continue;
                }
                String firstName=parentName;//一级分类
                String secondName=singleData.split(":")[0];
                String secondCode=singleData.split(":")[3];

                //重新创建分类
                System.out.println("重新创建该分类..."+isCreateFirstClass);
                if(isCreateFirstClass){
                    isSecondMode=false; //创建一级分类
                }else{
                    isSecondMode=true; //创建二级分类
                }
                String res=MeiTuan_CreateItem(firstName,isSecondMode,secondName,secondCode); //创建一级分类和二级分类
                System.out.println("----------------------");
                System.out.println("创建二级分类:");
                System.out.println(secondName+","+secondCode);
                System.out.println("创建结果:");
                System.out.println(res);
                System.out.println("----------------------");
                isCreateFirstClass=false;
                try { TimeUnit.MILLISECONDS.sleep( 100); } catch (InterruptedException e) { e.printStackTrace(); }
            }*/

        }
    }



    /*生成菜单地图*/
    /*
    *  {"水果蔬菜:fd","车厘子草莓:50:350:fd01","柑橘橙柚:50:400:fd02","瓜/奇异果:50:450:fd03","龙眼/枣/柿:50:500:fd04","热带水果:50:550:fd05","苹果梨蕉:50:600:fd06","箱装/果切:50:650:fd07","花果/茄瓜:50:700:fd08:Enter","根茎类:50:450:fd09","叶菜/结球类:50:500:fd10","豆制品:50:550:fd11","菌菇:50:600:fd12","调味菜:50:650:fd13","净菜:50:700:fd14"}
    * */
    public static void generatetemMap(int arrIndex,String classCode,String title,String pointX,String pointY){
        String data="";
        String EnterLine="";
        int num=arrIndex+1;
        if(arrIndex==0){
            if(SuperMarketSecondClass.filterWord(title)!="null"){
                data=title+":"+classCode; //"水果蔬菜:fd"
            }else{
                data="null";
            }
        }else{
            if(arrIndex==9){
                EnterLine=":Enter";
            }
            if(SuperMarketSecondClass.filterWord(title)!="null"){
                data=title+":"+pointX+":"+pointY+":"+classCode+((num<10)?"0"+num:num)+EnterLine; //"车厘子草莓:50:350:fd01" -- "青菜:50:350:fd01:EnterLine"
            }else{
                data="null";
            }
        }
        if(!StringUtils.isEmpty(data)){
            dataMapList.add(data); //过滤字符串
        }
    }














    /*获取所有类和id生成地图*/
    public static void getAllClassTitleAndIdToMap(String ResponseMessage){
        //转换格式为json
        JSONObject jsonObject = JSONObject.parseObject(ResponseMessage);
        JsonParser.traverseJson(jsonObject);
        try { TimeUnit.MILLISECONDS.sleep( 200); } catch (InterruptedException e) { e.printStackTrace(); }
        //遍历对象
        Map<String,Object> getAllJsonObject=JsonParser.getAllJsonObject;

        //StringBuilder DetailImagesList=new StringBuilder();
        JSONArray itemsList= (JSONArray) getAllJsonObject.get("goodsClassifyList");
        for (int i = 0; i < itemsList.size(); i++) {
            JSONObject obj = JSONObject.parseObject(itemsList.get(i).toString());
            System.out.println("类名:"+obj.getString("title")+":"+obj.getString("id"));
        }
    }


    /*删除一级分类及旗下商品*/
    public static String BatchDelete(String firstName,String AppPoiCode,Boolean isDeleteAll) throws Exception{
        MeiTuanBatchDelete mDelete=new MeiTuanBatchDelete();
        mDelete.setIsDeleteAll(isDeleteAll);
        mDelete.setApp_poi_code(AppPoiCode); //共享变量,当前门店id
        mDelete.setTimestamp(System.currentTimeMillis());
        if(!isDeleteAll){
            mDelete.setCategory_names(firstName); //要删除的一级分类名称，不传则删除所有分类
        }
        mDelete.setSignValue(mDelete.getSign());
        return mDelete.StartDelete();
    }


    /*创建美团分类*/
    public static String MeiTuan_CreateItem(String AppPoiCode,String firstClassName,Boolean isSecondMode,String secondClassName,String secondClassCode) throws Exception {
        CreateUpdateClass cu=new CreateUpdateClass();
        cu.setApp_poi_code(AppPoiCode); //共享变量,当前门店id
        cu.setIsCreate(true); //创建/或更新菜单
        cu.setIsCreateSecond(isSecondMode); //创建二级分类
        cu.setTimestamp(System.currentTimeMillis());
        cu.setFirstClass(firstClassName);
        String sname=FilterName(secondClassName); //过滤二级分类
        cu.setSecondClass(sname.length()>8?sname.substring(0,8):sname);
        cu.setSecondClassCode(secondClassCode);
        cu.setSignValue(cu.getSign());
        return cu.StartSetClass();
    }

    public static String FilterName(String inputString){
        String[] words=new String[]{"礼券"};
        String target = inputString;
        boolean found = false;
        for (String s : words) {
            if (target.indexOf(s)!=-1) {
                return target.replace(s,"");
            }
        }
        return target;
    }

    /*更新美团分类*/
    public static void MeiTuan_UpdateItem(int UpdateLeve,String firstClassName,String newFirstName,String secondClassName,String newSecondClassName,String secondClassCode) throws Exception {
        CreateUpdateClass cu=new CreateUpdateClass();
        cu.setApp_poi_code(curAppPoiCode); //共享变量,当前门店id
        cu.setIsCreate(false); //创建/或更新菜单
        cu.setTimestamp(System.currentTimeMillis());
        cu.setUpdateLevel(UpdateLeve);
        if(UpdateLeve==1){
            cu.setFirstClass(firstClassName);
            cu.setNewFirstClass(newFirstName);
        }
        if(UpdateLeve==2){
            cu.setSecondClass(secondClassName);
            cu.setNewSecondClass(newSecondClassName.length()>8?newSecondClassName.substring(0,8):newSecondClassName);
            cu.setSecondClassCode(secondClassCode);
        }

        cu.setSignValue(cu.getSign());
        cu.StartSetClass();
    }



} // class End
